import Vue from 'vue'
import App from './App.vue'
import router, { routes } from './router'
import store from './store/store'
// import { SET_CATEGORY } from '@/store/mutations'
import {
  Button,
  Field,
  Toast,
  Dialog,
  NavBar,
  Lazyload,
  Loading,
  Swipe,
  SwipeItem,
  Row,
  Col,
  Tabbar,
  TabbarItem,
  Icon,
  List,
  Popup,
  Checkbox,
  Tab,
  Tabs,
  SwipeCell,
  Collapse,
  CollapseItem,
  Cell,
} from 'vant'
import { sync } from 'vuex-router-sync'
import {
  SET_INST_INFO,
  SET_IP,
  SET_GOBACKNAME,
  SET_USER_INFO,
} from './store/mutations'
import http, { request } from './plugins/http.plugin'
import {
  AppInfo,
  connectWebViewJavascriptBridge,
  loading,
} from 'lib/appMethods'
import { parseQuery, isAndroid, setTitle, browser, isiOS, getTestTitle } from 'lib/utils'
import { setShareData } from './lib/share/share'
import { getShareInfo } from './lib/share/shareInfo'

Vue.config.productionTip = false

Vue.use(SwipeCell)
Vue.use(Tab).use(Tabs)
Vue.use(Popup)
Vue.use(NavBar)
Vue.use(Tabbar).use(TabbarItem)
Vue.use(Button)
Vue.use(Field)
Vue.use(Icon)
Vue.use(Toast)
Vue.use(Dialog)
Vue.use(Loading)
Vue.use(Swipe).use(SwipeItem)
Vue.use(Row).use(Col)
Vue.use(List)
Vue.use(Checkbox)
Vue.use(Collapse)
Vue.use(CollapseItem)
Vue.use(Tab)
Vue.use(Tabs)
Vue.use(Cell)
Vue.use(Lazyload, {
  lazyComponent: true,
  error: require('assets/default.jpg'),
  attempt: 2,
})

// Vue.directive('touch', vTouch)
Vue.use(http)
sync(store, router)

window.visitPageCount = 0

// ios从支付返回样式丢失问题
window.onpageshow = function (event: any) {
  if (event.persisted) {
    window.location.reload()
  }
}

const origin = location.origin || location.protocol + '//' + location.host
router.beforeEach((to, from, next) => {
  window.isPageLoading = true
  // AppInfo.callMethod('showLoading')
  if (!to.name) {
    next('/*')
    return
  }
  // 第一次进入时清除缓存
  const firstInto = localStorage.getItem('firstInto')
  // TODO: 删点firstInto === '1'
  if (!firstInto || +firstInto < 3) {
    localStorage.clear()
    localStorage.setItem('firstInto', '3')
  }
  // if (to.meta.requireCategory) {
  //   if (!store.state.category.CategoryId) {
  //     next({ name: 'selectCategory', query: { ...to.query, from: to.name, replace: '1' } })
  //     return
  //   }
  // }

  if (to.meta.requireAuth && store.state.userInfo.UserId === '-1') {
    sessionStorage.setItem(
      'loginFromPage',
      JSON.stringify({ from: to.name, query: to.query })
    )
    next({ name: 'login' })
  } else if (to.name === 'pay' && !to.query.code && browser.isWechat) {
    next(false)

    const appid = store.state.instInfo.WxAppId || 'wx47d745fcf21e7c4a'
    const payOrigin = store.state.instInfo.WxAppId
      ? origin.replace('test', '')
      : 'http://top.huikao8.cn'
    const wxPayUrl = encodeURIComponent(
      `${origin}${to.path}?orderId=${to.query.orderId}&orderNumber=${
        to.query.orderNumber
      }`
    )
    location.href = `${payOrigin}/get-weixin-code.html?appid=${appid}&scope=snsapi_base&redirect_uri=${wxPayUrl}`
    // }
  } else {
    // if (!(to.query.x666 || from.query.x666)) {
    //   loading.clear()
    //   loading.show('加载中...', `page#${to.name}`)
    // }
    next()
  }
})
// TODO: 改回注掉代码
let appLoadingHidden = !AppInfo.isApp
router.afterEach((to, from) => {
  if (!AppInfo.isApp) {
    // web页面设置分享内容, 所有页面都设置分享，非分享页分享到首页
    window.visitPageCount++
    // if (!to.meta.setSharePage && window.visitPageCount === 1) {
    //   configWX()
    // } else if (to.meta.setSharePage && to.meta.setSharePage !== 2) {
    const uname = to.query.uname as string
    const config = getShareInfo({
      routeName: (to.query.name as string) || to.name!,
      subject: (to.query.title || to.query.subj || to.meta.title) as string,
      userName: uname,
      sharePath: to.query.url as string,
    })
    // console.log(to.query.name, to.name, config)
    Vue.nextTick(() => {
      setShareData({
        ...config,
        imgUrl: `https:${store.state.instInfo.SchoolH5Logo}`,
        from: 'jggw',
      })
    })
    // }
  }

  if (to.query.userId) {
    if (to.name !== 'classDetail' && to.name !== 'shareOutPage') {
      request({
        url: 'User/InvitedInfo',
        method: 'get',
        data: {
          UserId: to.query.userId,
        },
      }).then(res => {
        if (res.OrangeKey) {
          localStorage.setItem('orangeKey', res.OrangeKey)
        }
      })
    }
  }

  if (!appLoadingHidden) {
    appLoadingHidden = true
    AppInfo.callMethod('hideLoading')
  }
  if (to.query.fromApp) {
    if (store.state.goBackName !== 'app') {
      store.commit(SET_GOBACKNAME, 'app')
    }
    if (!AppInfo.appName) {
      AppInfo.appName = parseQuery().fromApp
    }
  } else if (store.state.goBackName === 'app') {
    store.commit(SET_GOBACKNAME, '')
  }

  setTimeout(() => {
    // loading.hide(`page#${to.name}`)
    window.isPageLoading = false
  }, 50)
  if (to.meta.titleIsInstName) {
    setTitle('一通教育')
  } else {
    // eslint-disable-next-line eqeqeq
    let title = (to.meta.titleFrom && to.query.title) || to.meta.title
    if (to.name === 'examTest') {
      title = getTestTitle(to.query)
    }
    setTitle(title)
  }
})

// app内嵌页面
// if (parseQuery().fromApp && parseQuery().instId) {
//   AppInfo.isApp = true
//   require('scss/inApp.scss')
//   if (isAndroid) {
//     connectWebViewJavascriptBridge(getUserDataInApp)
//   } else {
//     getUserDataInApp()
//   }
//   // TODO: 临时添加，需要放开上面的
//   // initVue()
// }
// else {
//   // Promise.all([fetchInstInfo(), fetchIp()])
//   fetchInstInfo().then((instInfo: any) => {
//     if (instInfo.CategoryList.length > 0) {
//       const IndustryInfo = {
//         CategoryList: [ ...instInfo.CategoryList ],
//         IndustryId: 522,
//         IndustryName: '成人高考',
//       }
//       // store.commit(SET_CATEGORY, {
//       //   CategoryId: instInfo.CategoryList[0].CategoryId,
//       //   CategoryName: instInfo.CategoryList[0].CategoryName,
//       //   isAll: false,
//       //   IndustryInfo,
//       //   selectIndex: 0,
//       //   isSpecial: false,
//       //   isXueLi: true,
//       //   isAdultEducationInst: true,
//       // })
//     }
//     delete instInfo.CategoryList
//     store.commit(SET_INST_INFO, instInfo)
//     // store.commit(SET_IP, ip)
//     // routeTitleObj.Home = instInfo.TrainingName
//     initVue()
//     // if (instInfo.Mark === 1) {
//     //   router.replace({ name: 'outDate' })
//     // }
//   })
// }
initVue()

interface InstInfoData extends InstInfo {
  CategoryList: any[]
}
function fetchInstInfo (): Promise<InstInfoData> {
  // eslint-disable-next-line max-len
  const host =
    process.env.NODE_ENV === 'production'
      ? location.host
      : process.env.VUE_APP_FAKE_HOST!
  const instInfo = sessionStorage.getItem(host)
  if (instInfo) {
    return new Promise(resolve => {
      resolve(JSON.parse(instInfo))
    })
  } else {
    const modHost = host.indexOf('m.') === 0 || host.indexOf('testm.') === 0
      ? host.replace('m.', '') : host
    return request(
      {
        url: 'Training/SchoolInfoByUrl',
        method: 'get',
        data: {
          Url: modHost,
        },
      },
      {}
    ).then(res => {
      sessionStorage.setItem(host, JSON.stringify(res))
      return res
    })
  }
}
// function fetchIp () {
//   const ipAddr = sessionStorage.getItem('ipAddr')
//   if (ipAddr) {
//     return new Promise(resolve => {
//       resolve(ipAddr)
//     })
//   } else {
//     return request({
//       url: 'Account/GetIp',
//     }).then(res => {
//       sessionStorage.setItem('ipAddr', res)
//       return res
//     })
//   }
// }

function getUserDataInApp () {
  AppInfo.callMethod('getUserData', '', true).then(res => {
    store.commit(SET_USER_INFO, res)
    initVue()
  })
}
function initVue () {
  new Vue({
    router,
    store,
    render: h => h(App),
  }).$mount('#app')
}
